package cc.orange.mainView;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
//import com.tendcloud.tenddata.TalkingDataSDK;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import cc.orange.R;
import cc.orange.adapter.HomeAdapter;
import cc.orange.base.BaseFragment;
import cc.orange.databinding.FragmentHomeBinding;
import cc.orange.entity.ChatListEntity;
import cc.orange.entity.HightEntity;
import cc.orange.entity.HomeTotalNumEntity;
import cc.orange.entity.IsLoginsEntity;
import cc.orange.entity.LoginsEntity;
import cc.orange.entity.SuerInfosEntity;
import cc.orange.entity.UpdataUserPostEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.CheckNotifyPermissionUtils;
import cc.orange.utils.NotificaUtils;
import cc.orange.utils.RequestPermissions;
import cc.orange.utils.ZXToastUtil;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class HomeFragment extends BaseFragment implements View.OnClickListener{

    private FragmentHomeBinding binding;
    private HomeAdapter adapter;
    private List<ChatListEntity.Data.DataList> list = new ArrayList<>();
    private SuerInfosEntity entity;
    private ZXSharedPrefUtil sharedPrefUtil;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater,R.layout.fragment_home,container,false);
        sharedPrefUtil = new ZXSharedPrefUtil();
        initViews();
        chatList();
        EventBus.getDefault().register(this);
        return binding.getRoot();
    }


    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void getHight(SuerInfosEntity entity){
        if(entity.getCode() == 0){
            Log.v("----okhttps",""+entity);
            this.entity = entity;
            boolean b1 = CheckNotifyPermissionUtils.checkNotifyPermission(getActivity());
            Log.v("----okhttps2",""+b1);
            if(entity == null || entity.getData() == null){
                binding.msgRel2.setVisibility(View.GONE);
            }else {
                if (entity.getData().getNewsRemind().equals("0")) {//是否开启消息提醒(0关闭,1开启)
                    binding.msgRel2.setVisibility(View.VISIBLE);
                } else if (entity.getData().getNewsRemind().equals("1") && b1) {//是否开启消息提醒(0关闭,1开启)
                    binding.msgRel2.setVisibility(View.GONE);
                } else {
                    binding.msgRel2.setVisibility(View.VISIBLE);
                }
            }
        }else{

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void getHight(String entity){
        if(entity.equals("home_refres")){
            list.clear();
            chatList();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void initViews() {

        adapter = new HomeAdapter(list);
        binding.homeRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.homeRecycler.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String token_hr = sharedPrefUtil.getString("token_hr");
                boolean isLogin_hr = sharedPrefUtil.getBool("isLogin_hr");
                if(!isLogin_hr || TextUtils.isEmpty(token_hr)){
                    ZXToastUtil.showToast("请先登录");
                    startActivity(new Intent(getActivity(),LoginActivity.class));
                    return;
                }
                Intent intent = new Intent(getActivity(), ConversationListActivity.class);
                intent.putExtra("uid", "" + list.get(position).getWomanId());
                intent.putExtra("u_name",
                        ""+(TextUtils.isEmpty(list.get(position).getRemarkName()) ?
                                list.get(position).getName() : list.get(position).getRemarkName()));
                intent.putExtra("u_spare", "" + list.get(position).getSpareStatus());
                intent.putExtra("type_t", "0");
                startActivity(intent);
                list.get(position).setUnreadNum(0);
                adapter.notifyDataSetChanged();
            }
        });
        binding.msgRel2.setOnClickListener(this);
        binding.msgRel4.setOnClickListener(this);

    }



    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getHight(HightEntity entity) {//改变布局
        if(entity.getHight() > 0){
            RelativeLayout.LayoutParams pp = new RelativeLayout.
                    LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    entity.getHight());
            binding.msglistTitle.setLayoutParams(pp);
        }
    }



    @Override
    public void onResume() {
        super.onResume();
//        TalkingDataSDK.onPageBegin(getActivity().getApplicationContext(), this.toString());
    }

    @Override
    public void onPause() {
        if(!this.isHidden()){
//            TalkingDataSDK.onPageEnd(getActivity().getApplicationContext(), this.toString());
        }
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        String token_hr = sharedPrefUtil.getString("token_hr");
        boolean isLogin_hr = sharedPrefUtil.getBool("isLogin_hr");
        if(!isLogin_hr || TextUtils.isEmpty(token_hr)){
            ZXToastUtil.showToast("请先登录");
            startActivity(new Intent(getActivity(),LoginActivity.class));
            return;
        }
        switch (v.getId()){
            case R.id.msg_rel2://开启通知
                RequestPermissions.getPermissions_notfi(getActivity(), new RequestPermissions.SuccessInterf() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess() {
                        if(entity != null && entity.getData() != null ){
                            entity.getData().getNewsRemind().equals("1");
                            updateNotify();
                            list.clear();
                            chatList();
                        }else{
                            binding.msgRel2.setVisibility(View.GONE);
                        }

                    }
                });
                break;
            case R.id.msg_rel4://重要提示
                startActivity(new Intent(getActivity(),ConverNotesFActivity.class));
                break;
        }
    }

    private void updateNotify(){
        UpdataUserPostEntity entitys = new UpdataUserPostEntity();
      entitys.setNewsRemind("1");
        Gson gss = new Gson();
        String s = gss.toJson(entitys);
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .updateUser(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<LoginsEntity>() {
                    @Override
                    public void onStart(Call<LoginsEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<LoginsEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<LoginsEntity> call, LoginsEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            if(entity == null || entity.getData() == null)return;
                            entity.getData().setNewsRemind("1");
                            ZXToastUtil.showToast("已开启聊天消息提醒");
                            EventBus.getDefault().post(new String("getsus"));
                        }else{
                        }
                    }
                });
    }

    private void chatList() {
        RetrofitFactory.create(ApiService.class)
                .chatList(getTokens(),"0")//消息列表类型(0首页消息,1悄悄话消息)
                .enqueue(new DefaultCallback<ChatListEntity>() {
                    @Override
                    public void onStart(Call<ChatListEntity> call) {
                        showLoading_base(getActivity());
                    }

                    @Override
                    public void onError(Call<ChatListEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(Call<ChatListEntity> call, ChatListEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            list.addAll(baseEntity.getData().getDataList());
                            adapter.notifyDataSetChanged();
                            if(baseEntity.getData().getTotalNum() > 0 ){
                                if(entity == null || entity.getData() == null)return;
                                boolean b1 = CheckNotifyPermissionUtils.checkNotifyPermission(getActivity());
                               if(entity.getData().getNewsRemind().equals("1") && b1){//是否开启消息提醒(0关闭,1开启)
                                    NotificaUtils.gets(getActivity(),""+baseEntity.getData().getTotalNum());
                                }
                            }
                            EventBus.getDefault().post(new HomeTotalNumEntity(baseEntity.getData().getTotalNum()));
                        } else {
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }
}